package com.weiyu.bultrasound.core.controller;

import com.github.pagehelper.PageInfo;
import com.weiyu.bultrasound.core.model.common.JsonResult;
import com.weiyu.bultrasound.core.model.request.ApplyRequestBody;
import com.weiyu.bultrasound.core.model.request.CommonRequest;
import com.weiyu.bultrasound.core.model.request.UploadRequest;
import com.weiyu.bultrasound.core.model.response.CommonResponse;
import com.weiyu.bultrasound.core.model.response.ResponseHeader;
import com.weiyu.bultrasound.core.model.vo.ApplicationsVO;
import com.weiyu.bultrasound.core.service.ApplicationsService;
import com.weiyu.bultrasound.core.service.AsyncService;
import com.weiyu.bultrasound.core.service.FilesUploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 *@description 申请列表
 *@author abner chow
 *@date 2019-08-08 16:49
 */

@Api(description = "申请列表Api", tags = "ApplicationsController", basePath = "/applications")
@RestController
@RequestMapping(value = "/v1/applications", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class ApplicationsController {

    private static final Logger logger = LoggerFactory.getLogger(ApplicationsController.class);

    @Autowired
    ApplicationsService applicationsService;

    @Autowired
    FilesUploadService filesUploadService;

    @Autowired
    AsyncService asyncService;

    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token", required = false, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "【移动5G方调用】床旁医疗车相关文件导入接口", notes = "返回响应实体")
    @RequestMapping(value = "tMIMedCartApply", method = RequestMethod.POST)
    public CommonResponse tMIMedCartApply(@RequestBody CommonRequest<ApplyRequestBody> commonRequest) {
        CommonResponse result = new CommonResponse();
        ResponseHeader header = new ResponseHeader();
        try {
            result = applicationsService.tMIMedCartApply(commonRequest);
            header = result.getHeader();
        }catch (DuplicateKeyException e){
            logger.error(e.toString());
            header.setResultCode("1");
            header.setResultDesc("失败");
            header.setErrorCode("5001");
            header.setErrorInfo("有重复的申请代码，applyCode");
        }catch (Exception e) {
            logger.error(e.toString());
            header.setResultCode("1");
            header.setResultDesc("失败");
            header.setErrorCode("5000");
            header.setErrorInfo("服务器出错");
        } finally {
            header.setRequestId(commonRequest.getHeader().getRequestId());
            //生成响应id
            header.setResponseId(UUID.randomUUID().toString().replaceAll("-", ""));
            header.setTimeStamp(new Date().getTime());
            result.setHeader(header);
            result.setBody(commonRequest.getBody());
            return result;
        }

    }


    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token", required = false, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "【通用】根据id获取详情", notes = "返回单个申请详情")
    @RequestMapping(value = "get", method = RequestMethod.GET)
    public JsonResult<ApplicationsVO> get(@RequestParam(value = "id") Long id) {
        return JsonResult.getSuccessResult(applicationsService.getById(id));
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token", required = false, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "【通用】根据条件查询申请列表", notes = "返回分页列表")
    @RequestMapping(value = "getByPage", method = RequestMethod.GET)
    public JsonResult<PageInfo<ApplicationsVO>> getByPage(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                     @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                     @RequestParam(value = "patientName", required = false) String patientName,
                                                     @RequestParam(value = "handultSn", required = false) String handultSn,
                                                     @RequestParam(value = "status", required = false) String status) {
        Map condition = new HashMap<>();
        condition.put("pageNum", pageNum);
        condition.put("pageSize", pageSize);
        condition.put("patientName", patientName);
        condition.put("handultSn", handultSn);
        condition.put("status", status);
        return JsonResult.getSuccessResult(applicationsService.getByPage(condition));

    }


    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token", required = false, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "【移动端】上传保存文件", notes = "返回操作标识")
    @RequestMapping(value = "uploadFile", method = RequestMethod.POST)
    public JsonResult<Boolean> uploadFile(@RequestBody UploadRequest uploadRequest) {
        Boolean result = Boolean.FALSE;
        logger.info("开始保存移动端上传的文件记录");
        result = applicationsService.uploadFile(uploadRequest);
        if (result) {
            asyncService.asynFilesToFtp(uploadRequest.getId());
        }
        return JsonResult.getSuccessResult(result);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token", required = false, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "【通用】根据id获取同步文件数据", notes = "返回同步标识")
    @RequestMapping(value = "synFilesToFtp", method = RequestMethod.GET)
    public JsonResult<Boolean> synFilesToFtp(@RequestParam(value = "id") Long id) {
        return JsonResult.getSuccessResult(filesUploadService.synFilesToFtp(id));
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token", required = false, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "【移动端】判断申请单是否已上传", notes = "返回操作标识")
    @RequestMapping(value = "checkIfUpload", method = RequestMethod.GET)
    public JsonResult<Boolean> checkIfUpload(@RequestParam(value = "id") Long id) {
        Boolean result = Boolean.TRUE;
        ApplicationsVO applicationsVO = applicationsService.getById(id);
        if (null != applicationsVO) {
            if (applicationsVO.getStatus() == 3) {
                result = Boolean.TRUE;
            } else if (applicationsVO.getStatus() == 1) {
                result = Boolean.FALSE;
            }
        }
        return JsonResult.getSuccessResult(result);
    }

}
